package com.manor.common.utils

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.view.View
import android.widget.Button
import android.widget.ScrollView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatTextView
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.manor.common.CommonAppContext
import java.math.BigDecimal
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.regex.Pattern


fun copy(content: String, msg: String = "") {
    //获取剪贴板管理器：
    val cm = CommonAppContext.sInstance.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    // 创建普通字符型ClipData
    val mClipData =
        ClipData.newPlainText("Label", content)
    // 将ClipData内容放到系统剪贴板里。
    cm.setPrimaryClip(mClipData)
    if (!TextUtils.isEmpty(msg)){
        ToastUtils.showShort(msg)
    }

}

fun <T> getContent(t: T): String {
    var content = ""
    if (t is AppCompatEditText){
        content = t.text?.trim().toString()
    }
    if (t is AppCompatTextView){
        content = t.text?.trim().toString()
    }
    if (t is Button){
        content = t.text?.trim().toString()
    }
    if (t is AppCompatButton){
        content = t.text?.trim().toString()
    }
    return content
}

fun <T> getContentLength(t: T): Int {
    var length = 0
    if (t is AppCompatEditText){
        length = t.text?.trim().toString().length
    }
    if (t is AppCompatTextView){
        length = t.text?.trim().toString().length
    }
    return length
}
fun <T> isEmpty(t: T): Boolean{
    var content = ""
    if (t is AppCompatEditText){
        content = t.text?.trim().toString()
    }
    if (t is AppCompatTextView){
        content = t.text?.trim().toString()
    }
    if (t is String){
        content = t
    }
    return TextUtils.isEmpty(content)
}
fun isValidPhoneNumber(phoneNumber: String?): Boolean {
    return if (phoneNumber != null && !phoneNumber.isEmpty()) {
        Pattern.matches("^1[3-9]\\d{9}$", phoneNumber)
    } else false
}

/**
 * Scroll 截图
 * @param scrollView
 * @return
 */
fun shotScrollView(scrollView: ScrollView): Bitmap? {
    var h = 0
    val bitmap: Bitmap
    for (i in 0 until scrollView.childCount) {
        h += scrollView.getChildAt(i).height
    }
    bitmap = Bitmap.createBitmap(scrollView.width, h, Bitmap.Config.RGB_565)
    val canvas = Canvas(bitmap)
    scrollView.draw(canvas)
    return bitmap
}

fun View.v(v: Boolean?){
    if (v == true){
        this.visibility = View.VISIBLE
    }else{
        this.visibility = View.GONE
    }
}
fun TextView.content(content: Any?){
    this.text = content.toString()
}
fun View.iv(v: Boolean?){
    if (v == true){
        this.visibility = View.VISIBLE
    }else{
        this.visibility = View.INVISIBLE
    }
}

fun View.isVisible(): Boolean{
    return this.visibility == View.VISIBLE
}

fun String?.beColor(): String{
    return if (this.isNullOrEmpty()){
        "#000000"
    }else{
        if (this.startsWith("#")){
            this
        }else{
            "#$this"
        }
    }
}

/******************************************************** TextView样式 ********************************************************/
fun TextView.addMiddleLine(): TextView{
    this.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG // 设置
    return this
}
fun TextView.addBottomLine(): TextView{
    this.paint.flags = Paint. UNDERLINE_TEXT_FLAG
    return this
}
/******************************************************** Float 相关 ********************************************************/
fun <T> T?.back(back: String?): String? {
    val builder = java.lang.StringBuilder(this.toString())
    builder.append(back)
    return builder.toString()
}
fun <T> T?.front(front: String = "¥"): String? {
    val builder = StringBuilder(this.toString())
    builder.insert(0, front)
    return builder.toString()
}
fun <T> T?.frontAndBack(front: Any?, back: Any?): String? {
    if (null == this) {
        return ""
    }
    val builder = java.lang.StringBuilder(this.toString())
    builder.insert(0, front).append(back)
    return builder.toString()
}
fun <T> T?.keepPoints(point: Int): String? {
    val b = BigDecimal(this.toString())
    val dd: String
    dd = b.setScale(point, BigDecimal.ROUND_HALF_UP).toString()
    println(dd)
    return dd
}
fun add(value1: Any, value2: Any): Double {
    val b1 = BigDecimal(value1.toString())
    val b2 = BigDecimal(value2.toString())
    return b1.add(b2).toDouble()
}
fun sub(value1: Any, value2: Any): Double {
    val b1 = BigDecimal(value1.toString())
    val b2 = BigDecimal(value2.toString())
    return b1.subtract(b2).toDouble()
}
fun multiply(value1: Any?, value2: Any?): Double {
    val b1 = BigDecimal(value1.toString())
    val b2 = BigDecimal(value2.toString())
    return b1.multiply(b2).toDouble()
}
fun selected(vararg views: View){
    var view: View
    for (i in views.indices){
        view = views[i]
        view.isSelected = i == 0
    }
}
/**
 * 将米粒缩小的文字展示形式
 */
fun setWithRice(price: Any?, riceSize: Int = 9): SpannableStringBuilder{
    val spanString = SpannableStringBuilder(price.back("  米粒"))
    val absoluteSizeSpan = AbsoluteSizeSpan(riceSize.px)
    spanString.setSpan(
        absoluteSizeSpan,
        price.toString().length,
        price.toString().length + 4,
        Spannable.SPAN_INCLUSIVE_INCLUSIVE
    )
    return spanString
}
//复制沙盒私有文件到Download公共目录下
//orgFilePath是要复制的文件私有目录路径
//displayName复制后文件要显示的文件名称带后缀（如xx.txt）
//fun copyToDCIM(context: Context, orgFilePath: String?, displayName: String?) {
//    val values = ContentValues()
//    //values.put(MediaStore.Images.Media.DESCRIPTION, "This is a file");
//    values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, displayName)
//    values.put(MediaStore.Files.FileColumns.MIME_TYPE, "image/png") //MediaStore对应类型名
//    values.put(MediaStore.Files.FileColumns.TITLE, displayName)
//    values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM) //公共目录下目录名
//    val external: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI //内部存储的Download路径
//    val resolver = context.contentResolver
//    val insertUri: Uri? = resolver.insert(external, values) //使用ContentResolver创建需要操作的文件
//    var ist: InputStream? = null
//    var ost: OutputStream? = null
//    try {
//        ist = FileInputStream(File(orgFilePath))
//        if (insertUri != null) {
//            ost = resolver.openOutputStream(insertUri)
//        }
//        if (ost != null) {
//            val buffer = ByteArray(4096)
//            var byteCount = 0
//            while (ist.read(buffer).also { byteCount = it } != -1) {  // 循环从输入流读取 buffer字节
//                ost.write(buffer, 0, byteCount) // 将读取的输入流写入到输出流
//            }
//        }
//    } catch (e: IOException) {
//        ToastUtils.showShort("保存失败")
//        Log.i("copyPrivateToDownload--", "fail: " + e.cause)
//    } finally {
//        try {
//            ist?.close()
//            ost?.close()
//            ToastUtils.showShort("保存成功")
//        } catch (e: IOException) {
//            ToastUtils.showShort("保存失败")
//            Log.i("copyPrivateToDownload--", "fail in close: " + e.cause)
//        }
//    }
//}

/**
 * 获取app签名md5值
 */
fun getSignMd5Str(): String {
    try {
        val packageInfo = CommonAppContext.sInstance.packageManager.getPackageInfo(
                CommonAppContext.sInstance.packageName, PackageManager.GET_SIGNATURES
        )
        val signs: Array<Signature> = packageInfo.signatures
        val sign: Signature = signs[0]
        return encryptionMD5(sign.toByteArray())
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return ""
}
/**
 * MD5加密
 * @param byteStr 需要加密的内容
 * @return 返回 byteStr的md5值
 */
fun encryptionMD5(byteStr: ByteArray?): String {
    var messageDigest: MessageDigest? = null
    val md5StrBuff = StringBuffer()
    try {
        messageDigest = MessageDigest.getInstance("MD5")
        messageDigest.reset()
        messageDigest.update(byteStr)
        val byteArray: ByteArray = messageDigest.digest()
        for (i in byteArray.indices) {
            if (Integer.toHexString(0xFF and byteArray[i].toInt()).length == 1) {
                md5StrBuff.append("0").append(
                    Integer.toHexString(
                        0xFF and byteArray[i]
                            .toInt()
                    )
                )
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF and byteArray[i].toInt()))
            }
        }
    } catch (e: NoSuchAlgorithmException) {
        e.printStackTrace()
    }
    return md5StrBuff.toString()
}
fun getMillis(mill: Long): Long{
    return if (mill.toString().length <= 10){
        mill * 1000
    }else{
        mill
    }
}
val Float.px: Float get() = (this * Resources.getSystem().displayMetrics.density)

val Int.px: Int get() = ((this * Resources.getSystem().displayMetrics.density).toInt())



